from .models import UserProfile
from rest_framework.serializers import ModelSerializer
from rest_framework.exceptions import ValidationError
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User, Group, Permission, ContentType, AnonymousUser

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'

class ContentTypeSerializer(ModelSerializer):
    class Meta:
        model = ContentType
        fields = '__all__'

class PermSerializer(ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'
    # DRF中的嵌套序列化器，正常情况下 这个外键字段不显示 通过这个方式来获取一个ContentType对象。
    content_type = ContentTypeSerializer(read_only=True)

class UserSerializer(ModelSerializer):
    class Meta:
        model = UserProfile
        # fields = '__all__'
        fields = [
            'id', 'username', 'password', 'email',
            'is_active', 'is_superuser', 'phone'
        ]
        extra_kwargs = {
            'password': {'write_only':True},
            'username': {'max_length':16, 'min_length':4},
            'is_active': {'default':False},
            'is_superuser': {'default':False}
        }

    def validate_password(self, data):
        # regex实现密码强度校验
        # data是密码明文, 使用Django加密的方式make_password
        if 4 <= len(data) <= 16:
            return make_password(data)
        raise ValidationError("密码长度应该在4到16之间")


print('+' * 30)
print(UserSerializer())
